package com.xiaomaoguai.fcp;

import com.dh.conf.ZkClientProvider;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @fileName: ZkTool.java
 * @author: WeiHui
 * @date: 2018/11/15 21:10
 * @version: v1.0.0
 * @since JDK 1.8
 */
public class ZkToolForKepler {

	private static final String zkServers = "10.139.103.1:2181";

	protected String node;

	private String rootLocalFilepath = "D:\\workspace\\git\\za-collect\\plouto-test-tool\\src\\test\\resources/";

	private String path_handler = "D:\\workspace\\git\\za-collect\\plouto-test-tool\\src\\test\\resources\\kepler";

	private String rootNode = "/asset/za-fcp-pre-kepler";

	private ZkClient client;

	@Before
	public void before() {
		this.client = ZkClientProvider.getClient(zkServers, 5000);
	}

	@Test
	public void downZKAll() {
		try {
			download(rootLocalFilepath, rootNode);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void download(String parentPath, String zkNode) throws IOException {
		List<String> children = client.getChildren(zkNode);
		if (CollectionUtils.isNotEmpty(children)) {
			for (String child : children) {
				String content = client.readData(zkNode + "/" + child);
				//为空，建立目录
				if (StringUtils.isBlank(content)) {
					String filePath = parentPath + "/" + child;
					download(filePath, zkNode + "/" + child);
				} else {
					//不为空，下载文件
					String filePath = parentPath + "/" + child + ".json";
					File file = new File(filePath);
					FileUtils.touch(file);
					FileUtils.write(file, content, "UTF-8");
				}
			}
		}
	}


}
